/**
 * Created by huotaol on 2017/9/21.
 */
import React from "react";
import {Button, Form, Icon, Modal, Upload} from "antd";
import {get} from "@/axios/tools";
import {connect} from "react-redux";
import {handleUpload, UploadList} from "@/components/form/UploadList";

import {FoodForm} from "@/components/form/foodForm";
const Dragger = Upload.Dragger;

const previewFile = (file, callback) => {
    const reader = new FileReader();
    reader.onloadend = () => callback(reader.result);
    reader.readAsDataURL(file);
};

class AddFood extends React.Component {

    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            previewVisible: false,
            uploadVisible: false,
            previewImage: '',
            fileList: [],
            uploading: false,
            foodTypeList: [],
            // 已上传文件列表 {'id': 18, 'name': '土豆炖牛'}, {'id': 17, 'name': '红烧鲫鱼'}
            updateList: [],
            // 根据id 缓存 上传的文件列表
            uploadListOfId: {},
            currentFoodId: 0
        };
        this.handleChange = this.handleChange.bind(this);
        this.handleCancel = this.handleCancel.bind(this);
        this.handlePreview = this.handlePreview.bind(this);
    }

    handleCancel = () => this.setState({previewVisible: false});

    handleUpload = () => {
        const {currentFoodId, updateList} = this.state;
        handleUpload(currentFoodId, this.state);
        let newUpdateList = updateList.filter((item) => {
            return item.id !== currentFoodId;
        })
        this.setState({uploadVisible: false, updateList: newUpdateList});
    };

    handlePreview = (file) => {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true,
        });
    };

    handleChange(data) {
        const {file} = data;
        if (!file.url) {
            previewFile(file.originFileObj, (previewDataUrl) => {
                file.url = previewDataUrl;
                this.forceUpdate();
            })
        }

        const {fileList: files} = this.state;
        files.push(file);
        this.setListOfId(files);
        this.setState({fileList: files});
    };

    handleAfterSubmit = (data) => {
        const {updateList} = this.state;
        const {form} = this.props;

        let formValues = form.getFieldsValue();

        form.resetFields();
        updateList.push({
            id: data.id,
            ...formValues
        });
        this.setState({
            updateList
        });
    };

    onCheckChange = value => {
        console.log(' onCheckChange    ' + JSON.stringify(value));
    };

    setListOfId(files) {
        const {uploadListOfId, currentFoodId} = this.state;
        uploadListOfId[currentFoodId] = files.slice();
        this.setState({...uploadListOfId});
    };

    uploadImageById = (id) => {
        const {currentFoodId, uploadListOfId, fileList} = this.state;
        if (currentFoodId !== id) {
            // console.log(id, uploadListOfId[id]);
            this.setState({
                fileList: uploadListOfId[id] || []
            });
        }

        this.setState({
            currentFoodId: id,
            uploadVisible: true,
            ...uploadListOfId
        })
    };
    updateFileList = (data, key) => {
        key = key || 'fileList';
        // console.log(data)
        this.setListOfId(data);
        this.setState({[key]: data});
    };


    componentDidMount() {
        // this._requestMenus()
    };

    componentDidUpdate() {
        // console.log(this.refs.foodForm.state.fileList)
    };

    render() {
        const {previewVisible, previewImage, fileList, foodTypeList, uploadVisible} = this.state;
        const files = fileList instanceof Array ? fileList : Object.values(fileList);
        const uploadButton = (
            <div>
                <Icon type="plus"/>
                <div className="ant-upload-text">Upload</div>
            </div>
        );

        const uploadList = this.state.updateList.map((item, index) => {
            return (
                <div key={item.id} className="upload-item clearfix">
                    <span className="upload-field">
                        {item.id}  
                    </span>
                    <span className="upload-field">
                        {item.name}  
                    </span>
                    <span className="upload-field upload-btn">
                        <Button onClick={() => {
                            this.uploadImageById(item.id)
                        }}>上传图片</Button>
                    </span>
                </div>
            )
        });
        return (
            <div>
                <div className="clearfix content-container">
                    <FoodForm {...this.props} ref="foodForm" handleAfterSubmit={this.handleAfterSubmit}
                              foodTypeList={foodTypeList}/>
                    <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                        <img alt="example" style={{width: '100%'}} src={previewImage}/>
                    </Modal>
                    <Modal visible={uploadVisible} footer={null} onCancel={() => {
                        this.setState({
                            uploadVisible: false
                        })
                    }}>
                        <div className="clearfix">
                            {/* <Upload
                             fileList={fileList}
                             onPreview={this.handlePreview}
                             onChange={this.handleChange}
                             customRequest={() => {}}
                             showUploadList={false}
                             >


                             </Upload> */}
                            <div className="space-bar-25"></div>
                            <Dragger multiple onChange={this.handleChange} customRequest={() => {
                            }} showUploadList={false}>
                                <p className="ant-upload-drag-icon">
                                    <Icon type="inbox"/>
                                </p>
                                <p className="ant-upload-text">点击或拖拽上传文件</p>
                                <p className="ant-upload-hint">Support for a single or bulk upload. Strictly prohibit
                                    from uploading company data or other band files</p>
                            </Dragger>
                            <div className="space-bar"></div>
                            <UploadList fileList={files} state={this.state} updateFileList={this.updateFileList}/>
                        </div>
                        <div>
                            <Button
                                className="upload-demo-start"
                                type="primary"
                                onClick={this.handleUpload}
                                disabled={fileList.length === 0}
                                loading={this.state.uploading}
                            >
                                {this.state.uploading ? '上传' : '开始上传' }
                            </Button>
                        </div>
                    </Modal>
                </div>
                {
                    this.state.updateList.length ?
                        <div className="content-container">
                            {uploadList}
                        </div> : ''
                }
            </div>
        );
    }
}
const wrapperAddFood = Form.create()(AddFood);

const mapStateToProps = state => {
    const {auth = {data: {}}} = state.httpData;
    return {auth};
};

export default connect(mapStateToProps)(wrapperAddFood);